#include <iostream>
#include <vector>

#include <chrono>

#include <future>



// void Task(int num) {
// 	std::cout << num << std::endl;
// }

void MultiFuture() {

	std::future<int> future01 = std::async([&]() {
	std::cout << "future01" << std::endl;
	return 0;
	});

std::future<int> future02 = std::async([&]() {
	std::cout << "future02" << std::endl;
	return 0;
	});

std::future<int> future03 = std::async([&]() {
	std::cout << "future03" << std::endl;
	return 0;
	});

std::future<int> future04 = std::async([&]() {
	std::cout << "future04" << std::endl;
	return 0;
	});

std::future<int> future05 = std::async([&]() {
	std::cout << "future05" << std::endl;
	return 0;
	});

std::future<int> future06 = std::async([&]() {
	std::cout << "future06" << std::endl;
	return 0;
	});

	future01.get();
	future02.get();
	future03.get();
	future04.get();
	future05.get();
	future06.get();
}

// 无法编译通过，因为所需的future构造函数被删除了
// void MultiFutureInVector() {
// 	std::vector<std::future<int>> futures;
// 	for (int i = 0; i < 10; i++)
// 	{
// 		std::future<int> future_tmp = std::async([&]() {
// 			std::cout << "future " << i << std::endl;
// 			return 0;
// 		});

// 		futures.push_back(future_tmp);
// 	}
// }

// 仅仅只是按顺序创建future任务并执行而已
void MultiFutureInLoop() {
	for (int i = 0; i < 10; i++)
	{
		std::future<int> future_tmp = std::async([&]() {
			std::cout << "future " << i << std::endl;
			return 0;
		});
	}
}

// 暂时不明白这么写有什么意义
void MultiFutureInArray01() {
	const int numFutures = 10;
	std::future<int> int_futures_[numFutures];
	for (int i = 0; i < numFutures; i++)
	{
		int_futures_[i] = std::async([&]() {
			std::cout << "future value is " << i << std::endl;
			return 0;
		});
	}

	for (int i = 0; i < numFutures; i++)
	{
		// mythread[i].join();
		int_futures_[i].get();
	}
}

int printNum(int i) {
	while (true)
	{
		std::cout << "print " << i << std::endl;
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}

}

void MultiFutureInArray02() {
	const int numFutures = 10;
	std::future<int> int_futures_[numFutures];
	for (int i = 0; i < numFutures; i++)
	{
		// int_futures_[i] = std::async(std::launch::deferred, printNum, i);
		int_futures_[i] = std::async(std::launch::async, printNum, i);
	}

	for (int i = 0; i < numFutures; i++)
	{
		// mythread[i].join();
		int_futures_[i].get();
	}
}

void MultiFutureInPointer() {
	int numFutures = 10;
	std::future<int> *int_futures_ = new std::future<int>[numFutures];
	for (int i = 0; i < numFutures; i++)
	{
		// 在使用deferred模式下创建future，没有调用get的时候是不会运行的。
		// int_futures_[i] = std::async(std::launch::deferred, printNum, i);
		int_futures_[i] = std::async(std::launch::async, printNum, i);
	}

	for (int i = 0; i < numFutures; i++)
	{
		// mythread[i].join();
		int_futures_[i].get();
	}
}

int main() {
	// MultiFuture();

	// MultiFutureInLoop();
	// MultiFutureInArray01();
	// MultiFutureInArray02();
	MultiFutureInPointer();
	return 0;
}
